/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: CurrentFuturesEntrustOrderFragmentPresenter.java
 *   @Date: 19-6-25 上午11:46
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.presenter;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseListFreshPresenter;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NetWorkStatus;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.enums.ORDER_ENTRUST_TYPE;
import io.bhex.sdk.trade.futures.FuturesApi;
import io.bhex.sdk.trade.futures.bean.EntrustOrderResponse;
import io.bhex.sdk.trade.futures.bean.FutureStopProfitLossInfo;
import io.bhex.sdk.trade.futures.bean.FuturesOrderResponse;

public class CurrentFuturesEntrustOrderFragmentPresenter extends BaseListFreshPresenter<CurrentFuturesEntrustOrderFragmentPresenter.CurrentFuturesEntrustOrderFragmentUI> {
    private static final String LOGTAG = "CurrentOptionEntrustOrderFragmentPresenter";
    private List<FuturesOrderResponse> currentOrders = new ArrayList<>();
    private List<FuturesOrderResponse> currentPlanningOrders = new ArrayList<>();
    private List<FuturesOrderResponse> stopProfitLossOrders = new ArrayList<>();
    private String mPageIdOfOrdinary = "";
    private String mPageIdOfPlanning = "";
    private String mPageIdOfStopProfitLoss = "";
    private String currentOrderType = ORDER_ENTRUST_TYPE.LIMIT.getEntrustType();

    public interface CurrentFuturesEntrustOrderFragmentUI extends BaseListFreshPresenter.BaseListFreshUI {
        void showOrders(String entrustType, List<FuturesOrderResponse> currentOrders);
    }


    @Override
    public void onUIReady(BaseCoreActivity activity, CurrentFuturesEntrustOrderFragmentUI ui) {
        super.onUIReady(activity, ui);
        getOrdinaryData(false);
//        getPlanningData(false);
    }

    @Override
    public void getData(boolean isLoadMore) {
        if (currentOrderType.equals(ORDER_ENTRUST_TYPE.LIMIT.getEntrustType())) {
            getOrdinaryData(isLoadMore);
        }else if(currentOrderType.equals(ORDER_ENTRUST_TYPE.STOP.getEntrustType())){
            getPlanningData(isLoadMore);
        }else{
            getStopProfitLossData(isLoadMore);
        }
    }

    /**
     * 普通委托
     * @param isLoadMore
     */
    public void getOrdinaryData(final boolean isLoadMore) {
        currentOrderType = ORDER_ENTRUST_TYPE.LIMIT.getEntrustType();
        if (!UserInfo.isLogin()) {
            if (isLoadMore) {
                getUI().loadMoreComplete();
            }
            return;
        }
        if (!NetWorkStatus.isConnected(getActivity())) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }

        if (isLoadMore) {
            if (currentOrders != null) {
                if (!currentOrders.isEmpty()) {
                    mPageIdOfOrdinary = currentOrders.get(currentOrders.size() - 1).getOrderId();
                }
            }
        } else {
            mPageIdOfOrdinary = "";
        }

        String pageId = "";

        if (isLoadMore && !TextUtils.isEmpty(mPageIdOfOrdinary)) {
            //加载更多
            pageId = mPageIdOfOrdinary;

        }
        FuturesApi.RequestOpenOrder("", mPageIdOfOrdinary, "", AppData.Config.PAGE_LIMIT, "", currentOrderType, new SimpleResponseListener<EntrustOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
                if (isLoadMore) {
                    getUI().loadMoreComplete();
                }
            }

            @Override
            public void onSuccess(EntrustOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<FuturesOrderResponse> data = response.getArray();
                    if (data != null) {

                        if (isLoadMore) {
                            if (data != null) {
                                currentOrders.addAll(data);
                            }

                        } else {
                            if (data != null) {
                                currentOrders.clear();
                                currentOrders = data;
                            }
                        }
                        getUI().showOrders(ORDER_ENTRUST_TYPE.LIMIT.getEntrustType(),currentOrders);

                        if (data.size() < AppData.Config.PAGE_LIMIT) {
                            getUI().loadEnd();
                        } else {
                            getUI().loadMoreComplete();
                        }
                    } else {
                        getUI().loadMoreComplete();
                    }

                } else {
                    getUI().loadMoreFailed();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (isLoadMore) {
                    getUI().loadMoreFailed();
                }
            }
        });
    }

    /**
     * 计划委托
     * @param isLoadMore
     */
    public void getPlanningData(final boolean isLoadMore) {
        currentOrderType = ORDER_ENTRUST_TYPE.STOP.getEntrustType();
        if (!UserInfo.isLogin()) {
            if (isLoadMore) {
                getUI().loadMoreComplete();
            }
            return;
        }
        if (!NetWorkStatus.isConnected(getActivity())) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }

        if (isLoadMore) {
            if (currentPlanningOrders != null) {
                if (!currentPlanningOrders.isEmpty()) {
                    mPageIdOfPlanning = currentPlanningOrders.get(currentPlanningOrders.size() - 1).getOrderId();
                }
            }
        } else {
            mPageIdOfPlanning = "";
        }

        String pageId = "";

        if (isLoadMore && !TextUtils.isEmpty(mPageIdOfPlanning)) {
            //加载更多
            pageId = mPageIdOfPlanning;

        }
        FuturesApi.RequestOpenOrder("", mPageIdOfPlanning, "", AppData.Config.PAGE_LIMIT, "", currentOrderType, new SimpleResponseListener<EntrustOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
                if (isLoadMore) {
                    getUI().loadMoreComplete();
                }
            }

            @Override
            public void onSuccess(EntrustOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<FuturesOrderResponse> data = response.getArray();
                    if (data != null) {

                        if (isLoadMore) {
                            if (data != null) {
                                currentPlanningOrders.addAll(data);
                            }

                        } else {
                            if (data != null) {
                                currentPlanningOrders.clear();
                                currentPlanningOrders = data;
                            }
                        }
                        getUI().showOrders(ORDER_ENTRUST_TYPE.STOP.getEntrustType(), currentPlanningOrders);

                        if (data.size() < AppData.Config.PAGE_LIMIT) {
                            getUI().loadEnd();
                        } else {
                            getUI().loadMoreComplete();
                        }
                    } else {
                        getUI().loadMoreComplete();
                    }

                } else {
                    getUI().loadMoreFailed();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (isLoadMore) {
                    getUI().loadMoreFailed();
                }
            }
        });
    }

    /**
     * 查询止盈止损-当前委托单
     * @param isLoadMore
     */
    public void getStopProfitLossData(final boolean isLoadMore) {
        currentOrderType = ORDER_ENTRUST_TYPE.STOP_PROFIT_OR_LOSS.getEntrustType();
        if (!UserInfo.isLogin()) {
            if (isLoadMore) {
                getUI().loadMoreComplete();
            }
            return;
        }
        if (!NetWorkStatus.isConnected(getActivity())) {
            ToastUtils.showShort(getActivity(), getResources().getString(R.string.hint_network_not_connect));
            return;
        }

        if (isLoadMore) {
            if (stopProfitLossOrders != null) {
                if (!stopProfitLossOrders.isEmpty()) {
                    mPageIdOfStopProfitLoss = stopProfitLossOrders.get(stopProfitLossOrders.size() - 1).getOrderId();
                }
            }
        } else {
            mPageIdOfStopProfitLoss = "";
        }

        String pageId = "";

        if (isLoadMore && !TextUtils.isEmpty(mPageIdOfStopProfitLoss)) {
            //加载更多
            pageId = mPageIdOfStopProfitLoss;

        }
        FuturesApi.getStopProfitLossData("", mPageIdOfStopProfitLoss, "", AppData.Config.PAGE_LIMIT, "", new SimpleResponseListener<EntrustOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
                if (isLoadMore) {
                    getUI().loadMoreComplete();
                }
            }

            @Override
            public void onSuccess(EntrustOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<FuturesOrderResponse> data = response.getArray();
                    if (data != null) {

                        if (isLoadMore) {
                            if (data != null) {
                                stopProfitLossOrders.addAll(data);
                            }

                        } else {
                            if (data != null) {
                                stopProfitLossOrders.clear();
                                stopProfitLossOrders = data;
                            }
                        }
                        getUI().showOrders(ORDER_ENTRUST_TYPE.STOP_PROFIT_OR_LOSS.getEntrustType(), stopProfitLossOrders);

                        if (data.size() < AppData.Config.PAGE_LIMIT) {
                            getUI().loadEnd();
                        } else {
                            getUI().loadMoreComplete();
                        }
                    } else {
                        getUI().loadMoreComplete();
                    }

                } else {
                    getUI().loadMoreFailed();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (isLoadMore) {
                    getUI().loadMoreFailed();
                }
            }
        });
    }

    /**
     * 取消订单
     *
     * @param orderId
     * @param isBatch
     */
    public void cancelOrder(String clientOrderId, String orderId, String type, final boolean isBatch) {
        FuturesApi.orderCancel(clientOrderId, orderId, type, new SimpleResponseListener<ResultResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("", "");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    if (!isBatch) {
                        ToastUtils.showShort(getActivity(), getString(R.string.string_revoke_success));
                        getData(false);
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (!isBatch) {
                    ToastUtils.showShort(getActivity(), getString(R.string.string_revoke_failed));
                }
            }
        });
    }

    /**
     * 取消止盈止损单
     * @param clientOrderId
     * @param itemModel
     */
    public void cancelStopProfitLoss(String clientOrderId, FuturesOrderResponse itemModel) {
        if (itemModel == null) {
            return;
        }

        String isLong = KlineUtils.isFuturesLongOrder(itemModel.getSide())?"1":"0";
        FuturesApi.cancelStopProfitLossPrice(itemModel.getSymbolId(), isLong ,KlineUtils.isStopProfitOrder(itemModel.getPlanOrderType())?1:2,new SimpleResponseListener<FutureStopProfitLossInfo>(){
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(FutureStopProfitLossInfo response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    ToastUtils.showLong(getString(R.string.string_cancel_success));
                    getData(false);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }
}
